import requests
from bs4 import BeautifulSoup

# 发送HTTP请求
url = 'https://news.baidu.com/'  # 替换为你的目标URL
response = requests.get(url)

# 检查请求是否成功
if response.status_code == 200:
    # 解析HTML文档
    soup = BeautifulSoup(response.text, 'html.parser')
    #开始爬
    elements = soup.select('.hotnews ul li a')

    with open('test.txt', 'w', encoding='utf-8') as file:
    #遍历解析
        for i in elements :
            print(i.text)
            file.write(i.text+'\n')
else:
    print(f"请求失败，状态码：{response.status_code}")



